/*
 * @lc app=leetcode.cn id=238 lang=javascript
 *
 * [238] 除自身以外数组的乘积
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var productExceptSelf = function (nums) {
  const n = nums.length;
  const LtoR = new Array(n);
  const RtoL = new Array(n);
  LtoR[0] = nums[0];
  RtoL[n - 1] = nums[n - 1];
  for (let i = 1; i < n; i++) {
    LtoR[i] = LtoR[i - 1] * nums[i];
    RtoL[n - i - 1] = RtoL[n - i] * nums[n - i - 1];
  }
  const ans = new Array(n);
  for (let i = 0; i < n; i++) {
    let base = ans[i] === 0 ? 0 : 1;
    let L = LtoR[i - 1] ?? base;
    let R = RtoL[i + 1] ?? base;
    ans[i] = L * R;
  }
  return ans;
};
// @lc code=end
